package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.MessageAdapter;
import com.keyinong.caizhengting.entity.MessageEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：NewmessageActivity.java
 * @功能: 消息
 */

public class NewmessageActivity extends Activity {

    HttpTools httptools = null;
    /**
     * 上下拉刷新
     */
    private PullToRefreshListView pull_message;
    private ArrayList<MessageEntity> infolist;
    private MessageAdapter messageAdapter;
    private int offset = 0;
    private int page = 10;
    private String token;
    private ImageButton ib_back;
    /**
     * 没有消息
     */
    private TextView tv_state;
    private RelativeLayout rl_none;
    private OnItemClickListener itemclicke = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
//			Intent intent = new Intent();
//			intent.setClass(NewmessageActivity.this, NewxiaotieshiActivity.class);
//			intent.putExtra("id", infolist.get(position-1).getOrderid());
            if (!infolist.get(position - 1).getOrderid().equals("0") || !infolist.get(position - 1).getOrderid().equals("0")) {
                Intent intent = new Intent();
                intent.setClass(NewmessageActivity.this, DingdandetailActivity.class);
                intent.putExtra("orderid", infolist.get(position - 1).getOrderid());
                startActivity(intent);
            }
        }
    };
    /**
     * 上下拉刷新
     */
    private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset = 0;
            infolist.clear();
            httptools.getMessage(token, page + "", offset + "",
                    new JsonMessage());
            if (NetWorkUtil.isNetwork(NewmessageActivity.this) == false) {
                //				MyToast.mytoast(getActivity(), "当前网络不可用");
                Toast.makeText(NewmessageActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_message.onRefreshComplete();
                return;
            }

        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset += page;
            httptools.getMessage(token, page + "", offset + "",
                    new JsonMessage());
            //			setSection();
            //			adapter.notifyDataSetChanged();
            if (NetWorkUtil.isNetwork(NewmessageActivity.this) == false) {
                Toast.makeText(NewmessageActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_message.onRefreshComplete();
                return;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_newmessage);
        initRes();
    }

    private void initRes() {
        pull_message = (PullToRefreshListView) findViewById(R.id.pull_message);
        pull_message.setMode(Mode.BOTH);
        pull_message.setOnRefreshListener(onrefresh);
        pull_message.setOnItemClickListener(itemclicke);
        tv_state = (TextView) findViewById(R.id.tv_state);
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        ib_back = (ImageButton) findViewById(R.id.ib_back);
        tv_state = (TextView) findViewById(R.id.tv_state);
        rl_none = (RelativeLayout) findViewById(R.id.rl_none);
        ib_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Message();
    }

    /**
     * 获取新消息
     */
    private void Message() {
        infolist = new ArrayList<MessageEntity>();
        //		Log.i("shi", "token---" + token);
        if (httptools == null) {
            httptools = new HttpTools(NewmessageActivity.this);
        }
        httptools.getMessage(token, "" + page, "" + offset, new JsonMessage());
    }

    public class JsonMessage extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {

                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONArray array = response.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        String time = data.getString("time");
                        String content = data.getString("content");
                        String orderid = data.getString("orderid");
                        infolist.add(new MessageEntity(time, content, orderid));
                    }
                    Log.i("info", "----" + response.toString());
                    if (infolist.size() == 0) {
                        tv_state.setText("暂无信息");
                        rl_none.setVisibility(View.VISIBLE);
                    } else {
                        rl_none.setVisibility(View.GONE);
                    }
                    messageAdapter = new MessageAdapter(NewmessageActivity.this, infolist);
                    pull_message.setAdapter(messageAdapter);
                    pull_message.getRefreshableView().setSelection(offset);
                    pull_message.setDividerDrawable(null);
                    //				lv.setDivider(null);
                    //				Utility.setGridViewHeightBasedOnChildren(pull_twosort);
                    pull_message.onRefreshComplete();
                } else {
                    Toast.makeText(NewmessageActivity.this, msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}
